package view.diaLogView;

import android.annotation.TargetApi;
import android.app.Dialog;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.example.administrator.text.R;
import org.apache.log4j.Logger;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
import app.MyApplication;
import data.SharedPreferencesUtils;
import util.AgentIp;
import util.BReceiverUtil.SMSBroadcastReceiver;
import util.GreenTreeNetworkUtil;
import util.HomeUtil;
import util.JumpActivityUtils;
import util.LogUtil;
import util.NetWorkstateUtil;
import util.RequestDataCallback;
import util.StringUtil;
import util.Url;

/**
 * Created by liuxiaobin on 2016/11/24
 * 登录提示的Dialog   13049809642
 */
public class EntryPromptDialog extends Dialog implements View.OnClickListener{
    public final static String mStringEntry = "ENTRY";          //直接的登入(如深圳大学)
    public final static String mStringEntryHint = "ENTRYHINT";//登录(深职院)
    private Context mContext;
    private String mTypeStirng,mEntryType,mPhone,mAassword,mFwq;//diglog的类型 套餐地址 学生号 密码  mEntryType如果不为空代表是授权联网（sessionid） 为空就是深大联网
    private Logger mLogger = Logger.getLogger(EntryPromptDialog.class);
    private EntryPromptDialog mDialog;
    private boolean mJuderShow = true;
    public static HashMap<String,Object> mMap;       //访问网络
    public static boolean mJuderMessage = false;   //记录点击获取短信的次数
    private EditText mEditTextPhone;           //学生号输入框
    private EditText mEditTextPassword;       //密码输入框
    private EditText mETPhone;               //登入输入框
    private EditText mETPassword;           //登入输入框
    private TextView mTVverification;      //验证码
    private ImageView mImageView;
    private CheckBox mCheckBox;         //记住密码框
    private UploadDialog mUploadDialog;

    @Override public void show() {
        Window window = getWindow();
        window.setGravity(Gravity.BOTTOM);
        super.show();
    }

    public EntryPromptDialog(Context context,String type,String entryType) {
        super(context, R.style.upoad_dialog);
        this.mContext = context;
        this.mTypeStirng = type;
        this.mEntryType = entryType;
        mDialog = this;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        init();
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private void init() {
        ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        params.width = mContext.getResources().getDisplayMetrics().widthPixels;
        LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View mView = inflater.inflate(R.layout.entryprompt_dialog, null);
        setContentView(mView, params);
        RelativeLayout mRelativeLayout = (RelativeLayout)mView.findViewById(R.id.relati_entryprompt_beiji);
        RelativeLayout mRLEntryprompt = (RelativeLayout)mView.findViewById(R.id.relative_entryprompt);    //学生号和密码的输入框

        LinearLayout linearLayoutEntry = (LinearLayout)mView.findViewById(R.id.LinearLayout_entrydialog);
        TextView mTextViewHine1 = (TextView)mView.findViewById(R.id.text_entryprompt_hine1);
        TextView mTextViewHine2 = (TextView)mView.findViewById(R.id.text_entryprompt_hine2);

        TextView mTextViewHine = (TextView)mView.findViewById(R.id.text_entryprompt_hint);
        TextView mTextViewGouMai = (TextView)mView.findViewById(R.id.tv_entryprompt_goumai);          //购买套餐
        TextView mTextViewShaoDeng = (TextView)mView.findViewById(R.id.tv_entryprompt_shaodeng);     //稍等
        TextView mTextViewShengMing = (TextView)mView.findViewById(R.id.tv_entryprompt_statement);  //免责声明
        TextView mTVShengMing = (TextView)mView.findViewById(R.id.text_entry_statement);
        mEditTextPhone = (EditText)mView.findViewById(R.id.edittext_entryprompt_phone);
        EditText mETDialog = (EditText)mView.findViewById(R.id.etdialog_entry);
        mEditTextPassword = (EditText)mView.findViewById(R.id.edittext_entryprompt_password);

        mETPhone = (EditText)mView.findViewById(R.id.edit_entry_phone);
        mETPassword = (EditText)mView.findViewById(R.id.edit_entry_verification);
        mTVverification = (TextView)mView.findViewById(R.id.text_entry_verification);

        mImageView = (ImageView)mView.findViewById(R.id.edittext_entryprompt_show);
        mCheckBox = (CheckBox)mView.findViewById(R.id.checkbox_password);


        mETPhone.setOnClickListener(this);
        mETPassword.setOnClickListener(this);
        mTVverification.setOnClickListener(this);
        mTextViewGouMai.setOnClickListener(this);
        mTextViewShaoDeng.setOnClickListener(this);
        mCheckBox.setOnClickListener(this);
        mImageView.setOnClickListener(this);
        mTextViewShengMing.setOnClickListener(this);
        mTVShengMing.setOnClickListener(this);

       if(mTypeStirng.equals(mStringEntryHint)){
            linearLayoutEntry.setVisibility(View.VISIBLE);
            mTextViewHine1.setText("您还未登录"); mTextViewHine1.setTextColor(mContext.getResources().getColor(R.color.wecome));
            mTextViewHine2.setText("请先登录再进行操作"); mRelativeLayout.setBackgroundResource(R.drawable.retun_dialog);
            mRLEntryprompt.setVisibility(View.GONE); mTextViewHine.setVisibility(View.GONE); mTextViewGouMai.setText(mContext.getString(R.string.signin));
            String phone = (String) SharedPreferencesUtils.getParam(mContext, HomeUtil.mHUWePhone, "");
            if (!phone.equals("")) {
                mETPhone.setText(phone);
                mPhone = phone;
                mTVverification.setBackground(mContext.getResources().getDrawable(R.color.Land_true));
                mTVverification.setTextColor(mContext.getResources().getColor(R.color.bg_color));
            }
        }else if(mTypeStirng.equals(mStringEntry)){
          mRLEntryprompt.setVisibility(View.VISIBLE);
          linearLayoutEntry.setVisibility(View.GONE);
          mRelativeLayout.setBackgroundResource(R.drawable.retun_dialog);
          mTextViewHine1.setPadding(0,10,0,0);
          mTextViewHine1.setTextColor(mContext.getResources().getColor(R.color.wecome)); mTextViewHine.setVisibility(View.GONE);
         mTextViewHine2.setVisibility(View.GONE);
          String phone = (String) SharedPreferencesUtils.getParam(mContext,HomeUtil.mSTUDENPhone, "");
          String pwd = (String) SharedPreferencesUtils.getParam(mContext,HomeUtil.mSTUDENPSSWORD, "");
           if(mEntryType.equals("")){
               mTextViewHine1.setText("请输入校园卡号再联网");
               mTextViewGouMai.setText("联网");
           }else {
               mTextViewHine1.setText("请输入校园卡号再授权联网");
               mTextViewGouMai.setText("授权");
           }
          LogUtil.eE("szpwd",pwd);

            if(phone == null || phone.equals("")){
            }else {
                mEditTextPhone.setText(phone);
            }

            if(pwd.equals("")){
                mCheckBox.setChecked(true);
            }else {
                mEditTextPassword.setText((String) StringUtil.getStringUtilNew().stringObject(pwd));
                mCheckBox.setChecked(true);
            }
        }

        HomeUtil.getHemeUtilNew().getControlKeyboardLayout(mView,mETDialog);
        addText();
    }

    /**
     * 监听
     */
    private void addText() {

        //手机输入框的监听器
        mETPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            //变化中
            @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

                if (s.length() == 11) {
                    mTVverification.setBackground(mContext.getResources().getDrawable(R.color.Land_true));
                    mTVverification.setTextColor(mContext.getResources().getColor(R.color.bg_color));
                    mPhone= s.toString();
                } else if (s.length() < 11) {
                    mPhone = s.toString();
                    mTVverification.setTextColor(mContext.getResources().getColor(R.color.Land_true));
                    mTVverification.setBackground(mContext.getResources().getDrawable(R.drawable.entrydialog_verification));
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

        //学生号的输入框
        mEditTextPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            //变化中
            @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if(s.length() <= 2){
                    mEditTextPassword.setText("");
                }
            }
            @Override
            public void afterTextChanged(Editable s) {
            }
        });

    }

    /**
     * 登入
     */
    private void entry(){

        if (getEntryObtain()) {
            String string = HomeUtil.ENTRY;
            if(mEntryType.equals(HomeUtil.ZHUYENETWORKING)){
                string = HomeUtil.ZHUYENETWORKING;
            }else if(mEntryType.equals(HomeUtil.XIALA)){
                string = HomeUtil.XIALA;
            }else if(mEntryType.equals("1")||mEntryType.equals("2")||mEntryType.equals("3")||mEntryType.equals("4")||mEntryType.equals("5")){
                string = mEntryType;
            }else if(mEntryType.equals(HomeUtil.SZNETWORKING)){
                string = HomeUtil.SZNETWORKING;
            }

            HomeUtil.getHemeUtilNew().getEntry(mContext,mPhone,mAassword, new UploadDialog(mContext,mContext.getString(R.string.upload_hint)),mDialog,string);
        }
    }

    /**
     * 获取和验证登录信息
     */
    private boolean getEntryObtain() {

        mPhone = mETPhone.getText().toString().trim();
        mAassword = mETPassword.getText().toString().trim();
        if (!StringUtil.getStringUtilNew().isMobile(mPhone)) {
            Toast.makeText(mContext,"手机号不正确",Toast.LENGTH_SHORT).show();
            return false;
        }
        if (!StringUtil.getStringUtilNew().getStatePassword(mAassword)) {
            Toast.makeText(mContext,"密码或者验证码不正确",Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    private boolean getjumpBanDing(){
        mPhone = mEditTextPhone.getText().toString().trim();
        mAassword = mEditTextPassword.getText().toString().trim();

        if(mPhone.length() == 0 || mAassword.length() == 0){
            Toast.makeText(mContext,"学生号或密码为空",Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    /**
     * 系统返回键
     */
    @Override public boolean onKeyDown(int keyCode, KeyEvent event) {

        if(keyCode == KeyEvent.KEYCODE_BACK){
            mDialog.dismiss();}
        return true;
    }

    @Override public void onClick(View v) {
        int id = v.getId();
        String url = "file:///android_asset/xieyi.html";
        switch (id){
            case R.id.tv_entryprompt_shaodeng:
                    mDialog.dismiss();
                break;
            case R.id.tv_entryprompt_goumai:
                switch (mTypeStirng) {
                    case mStringEntry:
                        if(getjumpBanDing()){
                            getJudgeIP(0);
                        }
                        break;
                    case mStringEntryHint:
                        entry();
                        break;
                }
                break;
            case R.id.tv_entryprompt_statement:
                JumpActivityUtils.getInstance().jumpWebView(mContext, url,mContext.getString(R.string.statement_web));
                break;
            case R.id.text_entry_statement:
                JumpActivityUtils.getInstance().jumpWebView(mContext, url,mContext.getString(R.string.statement_web));
                break;
            case R.id.edittext_entryprompt_show:
                //第一次点击
                mAassword = mEditTextPassword.getText().toString().trim();
                if(mJuderShow){
                    mJuderShow = false;
                    mEditTextPassword.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);//密码可见
                    mImageView.setImageResource(R.mipmap.eye_true);
                    //第二次点击
                }else{
                    mJuderShow = true;
                    mImageView.setImageResource(R.mipmap.eye_false);
                    mEditTextPassword.setInputType(0x00000081);//密码可不见
                }

                mEditTextPassword.setText(mAassword);
                mEditTextPassword.setSelection(mAassword.length());
                break;
            case R.id.text_entry_verification:
                getVerification();
                break;
        }
    }

    private void getVerification(){
        mPhone = mETPhone.getText().toString().trim();
        if(StringUtil.getStringUtilNew().isMobile(mPhone)){
                if(!mJuderMessage){
                    HomeUtil.getHemeUtilNew().getMessage(mContext,mETPassword,new SMSBroadcastReceiver());
                    mMap = new HashMap<>();
                    mMap.put("phone",mPhone);    mMap.put("authCodeType",0);
                    String stringJson = StringUtil.getStringUtilNew().hashMapToJson(mMap); //参数包
                    long time = StringUtil.getStringUtilNew().getTimeCurrent();
                    String stirngSign = StringUtil.getStringUtilNew().getSign(Url.mStirngPhoneVerification,stringJson,"null","0",time);
                    Map map1 = StringUtil.getStringUtilNew().getMapNew(mContext,stringJson,"null","0",Url.mStirngPhoneVerification,stirngSign,time);
                    HomeUtil.getHemeUtilNew().obtainVerification(mContext,map1, MyApplication.getApp().getFWQString(),mTVverification,0,0);
                    mJuderMessage=true;
                }else {
                    PhoneMessageDialog phoneMessageDialog = new PhoneMessageDialog(mContext,mPhone,MyApplication.getApp().getFWQString(),mETPassword,mTVverification);
                    phoneMessageDialog.show();
                }
        }else {
            Toast.makeText(mContext,mContext.getString(R.string.no_phone),Toast.LENGTH_SHORT).show();
            }
    }

    /**
     * 判断之前ip是否可用
     * type 0 一进来
     * 1 web页面发来的地址
     */
    private void getJudgeIP(int judeg){
        String stringJson ="{}"; //参数包
        if(mUploadDialog == null){
            mUploadDialog = new UploadDialog(mContext,"连接中");
            mUploadDialog.show();
        }else {
            mUploadDialog.show();
        }
        final long time = StringUtil.getStringUtilNew().getTimeCurrent();
        String stirngSign = StringUtil.getStringUtilNew().getSign(Url.mStirngVersion_isAlive,stringJson,"null","0",time);
        Map map = StringUtil.getStringUtilNew().getMapNew(mContext,stringJson,"null","0",Url.mStirngVersion_isAlive,stirngSign,time);
        if(judeg == 0){
            mFwq = (String) SharedPreferencesUtils.getParam(mContext,HomeUtil.mFWQ,"");
        }
        mLogger.info("找ip-->getJudgeIP--->"+"fwq--"+mFwq+"type--"+"time"+StringUtil.getStringUtilNew().getTimeInstance());
        GreenTreeNetworkUtil.getInstance().doPost(mContext,mFwq,2000,map,new RequestDataCallback() {
            @Override public void onSuccess(String response) {
                try {
                    mLogger.info("getJudgeIP--->onSuccess--->"+"String--"+response);
                    JSONObject jsonObject = new JSONObject(response);
                    if (jsonObject.getInt("code") == 1) {
                        if (!mFwq.equals(Url.getUrlNew().getAppIP())) {
                            SharedPreferencesUtils.setParam(mContext, HomeUtil.mFWQ, mFwq);
                           }
                            MyApplication.getApp().setFWQString(mFwq);
                            //应该是在验证上网成功后保存
                            boolean checBox = mCheckBox.isChecked();
                            LogUtil.eE("szpwd",checBox+"");
                            mUploadDialog.getStringShow("联网中");
                            //NetWorkstateUtil.getInstance().setmNetWorkstateFail(0);
                            NetWorkstateUtil.getInstance().getNetworkingSZ(mContext,mPhone,mAassword,mUploadDialog,checBox,mDialog,mEntryType);
                    }else if(jsonObject.getInt("code") == -1){
                        Toast.makeText(mContext,mContext.getString(R.string.FWQ),Toast.LENGTH_SHORT).show();
                        if(mUploadDialog !=null){mUploadDialog.dismiss();}
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    mUploadDialog.dismiss();
                }
            }

            @Override public void onFailure(Throwable error) {
                mLogger.info("getJudgeIP()--->onFailure()--->代码没走通"+"Throwable--"+error);
                AgentIp.newInstance(mContext).getIp(new AgentIp.OnAgentIpItemClickListener() {
                    @Override
                    public void onItemClick(String fwq) {
                        mLogger.info("getJudgeIP()--->onFailure()--->onItemClick()网页获取的地址"+"String--"+fwq);
                        if(fwq.equals("没有查到")){
                            Toast.makeText(mContext,"没有查找到代理服务器",Toast.LENGTH_SHORT).show();
                            mUploadDialog.dismiss();
                        }else {
                            if (!fwq.equals(Url.getUrlNew().getAppIP())) {
                                SharedPreferencesUtils.setParam(mContext, HomeUtil.mFWQ, fwq);
                                MyApplication.getApp().setFWQString(fwq);
                                //应该是在验证上网成功后保存
                                boolean checBox = mCheckBox.isChecked();
                                LogUtil.eE("szpwd",checBox+"");
                                mUploadDialog.getStringShow("联网中");
                                //NetWorkstateUtil.getInstance().setmNetWorkstateFail(0);
                                NetWorkstateUtil.getInstance().getNetworkingSZ(mContext,mPhone,mAassword,mUploadDialog,checBox,mDialog,mEntryType);
                            }else {
                                Toast.makeText(mContext,"没有查找到代理服务器",Toast.LENGTH_SHORT).show();
                                mUploadDialog.dismiss();
                            }
                        }
                    }
                });
            }
        });
    }

    @Override
    public void dismiss() {
        LogUtil.eE("","..........EntryPromptDialog............");
        if(mUploadDialog !=null){mUploadDialog.dismiss();}
        super.dismiss();
    }
}
